package com.treeroot.smsservice.controller;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.treeroot.commonutils.AOP.Limit;
import com.treeroot.commonutils.result.R;
import com.treeroot.commonutils.utils.RandomUtil;
import com.treeroot.smsservice.service.SmsService;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;


/**
 * @Description:
 * @Author:treeRoot
 * @Email:553503639@qq.com
 * @Date: Create in 23:45 / 2022/5/17
 */
//TODO：短信发送模块移植公共模块

@RestController
@RequestMapping("/tencentSms")
@Api(description = "验证码")
public class MsmController {
    @Autowired
    private SmsService smsService;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @GetMapping("send/{phone}")
    @Limit(key = "send", permitsPerSecond = 1, timeout = 100, msg = "当前排队人数较多，请稍后再试！")
    @HystrixCommand(fallbackMethod = "sendFallback")

    public R send(@PathVariable String phone) {
        // 1.从redis获取验证码，如果获取到直接返回
        String code = redisTemplate.opsForValue().get(phone);
        if (!StringUtils.isEmpty(code)) {
            return R.ok();
        }
        //2.如果redis获取不到，进行腾讯云发送
        //生成随机值 腾讯云发送
        code = RandomUtil.getSixBitRandom();
        Map<String, Object> param = new HashMap<>();
        param.put("code", code);

        //调用service发送请求
        boolean isSend = smsService.send(code, phone);
        if (isSend) {
            //发送成功，把发送成功验证码放到redis里面
            // 设置有效时间 3分钟内有效
            redisTemplate.opsForValue().set(phone, code, 3, TimeUnit.MINUTES);

            return R.ok().message(code);
        } else
            return R.error().message("短信发送失败");
    }

    public R sendFallback(@PathVariable String phone){
        return   R.error().message("操作异常/系统异常");

    }

}
